import { constantRoutes,asyncRoutes } from '@/router'
// import { getRouters } from '@/api/menu'
import Layout from '@/layout'
export function filterAsyncRoutes(routes) {
  return routes.filter((route) => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } 
      // else if (route.component === 'ParentView') {
      //   route.component = ParentView
      // }
       else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRoutes(route.children)
    }
    return true
  })
}

export const loadView = (view) => {
  // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}
const state = {
  roles: [],
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      // getRouters().then((res) => {
        // const menuData = res.data.data
        // const menuData = []
        const accessedRoutes = filterAsyncRoutes(asyncRoutes)
        commit('SET_ROUTES', accessedRoutes)
        commit('SET_ROLES', [1, 2])
        resolve(accessedRoutes)
      })
    // })
  },
  delRouter({ commit }) {
    return new Promise((resolve) => {
      commit('SET_ROLES', [])
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
